package com.leyou.search.mq;

import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息队列 - 消费者
 */
@Component
public class ItemListener {

    /**
     * 搜索服务
     */
    @Autowired
    private SearchService searchService;

    /**
     * 新增/修改 索引库记录
     * @param spuId     商品 id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "search.item.insert.queue", durable = "true"),
            exchange = @Exchange(name = "ly.item.exchange", type = ExchangeTypes.TOPIC),
            key = {"item.insert", "item.update"})
    )
    public void listenInsertOrUpdate(Long spuId) {
        if (spuId == null) {
            return;
        }
        // 处理消息，新增/修改 索引库
        searchService.saveOrUpdateIndex(spuId);
    }

    /**
     * 删除索引库记录
     * @param spuId     商品 id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "search.item.delete.queue", durable = "true"),
            exchange = @Exchange(name = "ly.item.exchange", type = ExchangeTypes.TOPIC),
            key = {"item.delete"})
    )
    public void listenDelete(Long spuId) {
        if (spuId == null) {
            return;
        }
        // 处理消息，新增/修改 索引库
        searchService.deleteIndex(spuId);
    }
}
